#include <iostream>
#include <cstdlib>
#include <Network.hpp>

using namespace std;

using namespace Network;
using namespace System;


class ClientThread : public Thread
{
	protected:
	
	TcpSocket _csock;
	Mutex _mput;
	
	
	public:
	
	ClientThread(const TcpSocket& sock) : _csock(sock)
	{
		
	}
	
	
	protected:
	
	void run()
	{
		const IpEndPoint& ep = _csock.remoteEndPoint();
		putMsg("A client join has joined the server from "+ ep.ip());
		
		try
		{
			const int bufflen = 5;
			ByteArray buff(bufflen);
			
			// recoit 5 octets depuis le réseau
			_csock.recv(buff, bufflen);
			
			// Si ces 5 octet sont hello
			if(buff == "hello")
			{
			    // On envoi message_ok
				_csock.send("message_ok");
			}
			else
			{
			    // On envoi mess_error
				_csock.send("mess_error");
			}
		}
		catch(SocketException& e){}
				
		delete this;
	}
	
	void putMsg(const string& msg)
	{
		_mput.lock();
		cout << msg << endl;
		_mput.unlock();
	}
};



int main(/*int argc, char* argv[]*/)
{
	try
	{
		load();
		
		TcpSocket sock;
		sock.bind(IpEndPoint(IpAddress("0.0.0.0"), 1080));//IpAddress::ipv4_any
		sock.listen(5);
		
		cout << "Waiting new clients..." << endl;
		
		while(true)
		{
			ClientThread* thread = new ClientThread(sock.accept());
			thread->start();
		}
		
		unload();
	}
	catch(SocketException& e)
	{
		cout << "Critical error : " << e.what() << endl;
	}
}



